#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define PREV_INUSE 0x1
#define IS_MMAPPED 0x2
#define NON_MAIN_ARENA 0x4

#define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
#define chunksize_nomask(p)         ((p)->mchunk_size)
/* Get size, ignoring use bits */
#define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))

typedef struct _m_chunk {
	size_t mchunk_prev_size;
	size_t mchunk_size;
	//void* fd;
	//void* bk;
	//void* fd_nextsize;
	//void* bk_nextsize;
} m_chunk;

#define PRINT_BRK printf("break = %p\n", sbrk(0))
int main() {
	void* heap_begin = sbrk(0);
	printf("heap begin = %p\n", heap_begin);
	void* a = malloc(9);
	printf("break = %p, a = %p\n", sbrk(0), a);
	void* b = malloc(40);
	printf("break = %p, b = %p\n", sbrk(0), b);
	void* c = malloc(1);
	printf("break = %p, c = %p\n", sbrk(0), c);
	
	m_chunk* ap = (m_chunk*) ((char*)a - 8);
	m_chunk* bp = (m_chunk*) ((char*)b - 8);
	m_chunk* cp = (m_chunk*) ((char*)c - 8);

	printf("ap = %p, bp = %p, cp =%p\n", ap, bp, cp);
	printf("a chunk prev size = %d, size = %d\n", ap->mchunk_prev_size, chunksize(ap));
	printf("b chunk prev size = %d, size = %d\n", bp->mchunk_prev_size, chunksize(bp));
	printf("c chunk prev size = %d, size = %d\n", cp->mchunk_prev_size, chunksize(cp));
	
	memset(a, 1, 9);
	printf("b chunk prev size = %d, size = %d\n", bp->mchunk_prev_size, chunksize(bp));
	free(a);PRINT_BRK;free(b);PRINT_BRK;free(c);PRINT_BRK;
	return 0;
}
